package com.only4play.practice.pay.reconcile.core.strategy.download;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.alipay.api.AlipayApiException;
import com.alipay.api.domain.AlipayDataDataserviceBillDownloadurlQueryModel;
import com.ijpay.alipay.AliPayApi;
import com.ijpay.alipay.AliPayApiConfig;
import com.ijpay.alipay.AliPayApiConfigKit;
import com.ijpay.core.enums.SignType;
import com.ijpay.core.kit.WxPayKit;
import com.ijpay.wxpay.model.DownloadBillModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * @author mengdy
 */
@Component
@Slf4j
public class AliPayBillFileDownStrategy{


    private static final String IS_SANDBOX = "sandbox";

    public InputStream getBillFileInputStream(Map<String,String> params){
        int retryTimesParams = Integer.parseInt(params.get("retryTimes") == null ? "3" : params.get("retryTimes"));
        InputStream inputStream = null;
        int retryTimes = 0;
        while (inputStream == null && retryTimes++ < retryTimesParams){
            try{
                // 是否沙箱环境
                String sandbox = params.get(WeChatParamNameConstant.IS_SANDBOX);

                // 接口加签方式
                String interfaceSignType = params.get(AliParamNameConstant.INTERFACE_SIGN_TYPE);
                // 默认密钥模式
                if (StrUtil.isEmpty(interfaceSignType)){
                    interfaceSignType = AliParamNameConstant.INTERFACE_SIGN_TYPE_VALUE_SECRET;
                }
                // 是否服务商模式
                String isParentServe = params.get(AliParamNameConstant.IS_PARENT_SERVE);
                // 默认为非服务商模式
                if (StrUtil.isEmpty(isParentServe)){
                    isParentServe = AliParamNameConstant.VALUE_FALSE;
                }
                String appId = params.get(AliParamNameConstant.APPID);

                String billDate = params.get(AliParamNameConstant.BILL_DATE);
                String billType = params.get(AliParamNameConstant.BILL_TYPE);
                String tarType = params.get(AliParamNameConstant.BILL_TAR_TYPE);

                String privateKey = params.get(AliParamNameConstant.PRIVATE_KEY);
                String publicKey = params.get(AliParamNameConstant.PUBLIC_KEY);
                String appCertPath = params.get(AliParamNameConstant.APP_CERT_PATH);
                String appCertB64 = params.get(AliParamNameConstant.APP_CERT_B64);
                String alipayCertPath = params.get(AliParamNameConstant.ALIPAY_CERT_PATH);
                String alipayCertB64 = params.get(AliParamNameConstant.ALIPAY_CERT_B64);
                String alipayRootCertPath = params.get(AliParamNameConstant.ALIPAY_ROOT_CERT_PATH);
                String alipayRootCertB64 = params.get(AliParamNameConstant.ALIPAY_ROOT_CERT_B64);
                String appAuthToken = params.get(AliParamNameConstant.APP_AUTH_TOKEN);

                // TODO 使用步骤1 初始化支付宝客户端参数
                AliPayApiConfig apiConfig = null;
                // 普通密钥模式
                if (ObjUtil.equals(
                        AliParamNameConstant.INTERFACE_SIGN_TYPE_VALUE_SECRET,
                        interfaceSignType)){
                    log.info("使用密钥模式");
                    apiConfig = AliPayApiConfig.builder()
                            // 支付宝应用id
                            .setAppId(appId)
                            // 设置商户应用私钥
                            .setPrivateKey(privateKey)
                            .setAliPayPublicKey(publicKey)
                            .setCharset("UTF-8")
                            .setServiceUrl(ObjUtil.equals(sandbox, AliParamNameConstant.VALUE_TRUE) ?
                                    AliParamNameConstant.ALIPAY_SERVER_GATEWAY_SANDBOX :
                                    AliParamNameConstant.ALIPAY_SERVER_GATEWAY_PROD)
                            .setSignType("RSA2")
                            .build();

                }else if (ObjUtil.equals(
                        AliParamNameConstant.INTERFACE_SIGN_TYPE_VALUE_CERT,
                        interfaceSignType
                )){
                    log.info("使用证书模式");
                    apiConfig = AliPayApiConfig.builder()
                            // 支付宝应用id
                            .setAppId(appId)
                            // 设置商户应用私钥
                            .setPrivateKey(privateKey)
                            // TODO 这里要不要公钥？
                            //.setAliPayPublicKey(publicKey)
                            .setAppCertPath(appCertB64)
                            .setAliPayCertPath(alipayCertB64)
                            .setAliPayRootCertPath(alipayRootCertB64)
                            .setCharset("UTF-8")
                            .setServiceUrl(ObjUtil.equals(sandbox, AliParamNameConstant.VALUE_TRUE) ?
                                    AliParamNameConstant.ALIPAY_SERVER_GATEWAY_SANDBOX :
                                    AliParamNameConstant.ALIPAY_SERVER_GATEWAY_PROD)
                            .setSignType("RSA2")
                            .buildByCert();
                }else {
                    throw new RuntimeException("不支持的加签方式");
                }
                // 设置全局配置
                AliPayApiConfigKit.setThreadLocalAliPayApiConfig(apiConfig);
                AlipayDataDataserviceBillDownloadurlQueryModel model = new AlipayDataDataserviceBillDownloadurlQueryModel();
                model.setBillDate(billDate);
                model.setBillType(billType);
                String responseStr = AliPayApi.billDownloadUrlQuery(model);
                log.info("获取支付宝对账文件输入流返回结果：" + responseStr);

            }catch (Exception e){
                if (e instanceof AlipayApiException){
                    log.error("支付宝对账文件下载异常：" + e.getMessage());
                    inputStream = new ByteArrayInputStream(e.toString().getBytes());
                    return inputStream;
                }
                throw new RuntimeException(e);
            }
        }
        return null;
    }


    public static File downloadFile(Map<String,String> params) throws Exception{

        // 是否沙箱环境
        String sandbox = params.get(IS_SANDBOX);

        // 是否服务商模式
        String isParentServe = params.get("isParentServe");
        String appId = params.get("appId");
        String mchId = params.get("mchId");
        String subMchNo = params.get("subMchNo");
        String subAppId = params.get("subAppId");

        String billDate = params.get("billDate");
        String billType = params.get("billType");

        String partnerKey = params.get("partnerKey");

        DownloadBillModel.DownloadBillModelBuilder builder = DownloadBillModel.builder();
        // 是否服务商模式
        if (Integer.parseInt(isParentServe) == 1) {
            builder.appid(appId)
                    .mch_id(mchId)
                    .sub_appid(subAppId)
                    .sub_mch_id(subMchNo);
        } else {
            builder.appid(appId)
                    .mch_id(mchId);
        }

        DownloadBillModel downloadBillModel = builder.bill_date(billDate)
                .bill_type(billType)
                .nonce_str(WxPayKit.generateStr())
                .build();

        Map<String, String> reqParams = downloadBillModel.createSign(partnerKey, SignType.HMACSHA256);


        return null;
    }

    public static void main(String[] args) throws Exception {

        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("channelCode","aliPay");
        hashMap.put("billDate","2020-09-01");
        hashMap.put("billType","trade");
        hashMap.put("channelMchId","");
        hashMap.put("channelMchName","");

        File downloadFile = downloadFile(hashMap);

        System.out.println("hello world  " + downloadFile);
    }
}
